package cn.ihoway.impl;

import cn.ihoway.dao.AllocationDao;
import cn.ihoway.entity.Allocation;
import cn.ihoway.service.AllocationService;
import cn.ihoway.util.MybatisUtils;
import org.apache.ibatis.session.SqlSession;

import java.util.ArrayList;
import java.util.List;

public class AllocationServiceImpl implements AllocationService {

    private final SqlSession sqlSession = MybatisUtils.getSqlSession();
    private final AllocationDao allocationDao = sqlSession.getMapper(AllocationDao.class);

    @Override
    public Allocation search(String sessionId){
        return allocationDao.searchBySessionId(sessionId);
    }

    @Override
    public int delete(String sessionId){
        int rs = allocationDao.deleteBySessionId(sessionId);
        if(rs > 0){
            sqlSession.commit();
        }else {
            sqlSession.rollback();
        }
        return rs;
    }

    @Override
    public ArrayList<Allocation> searchMore(String roomId, Integer start, Integer end) {
        ArrayList<Allocation> list = new ArrayList<>();
        for(int i = start;i <= end; i++){
            Allocation allocation = allocationDao.searchByPlayerId(roomId,String.valueOf(i));
            list.add(allocation);
        }
        return list;
    }

    @Override
    public List<Allocation> searchMore(String roomId) {
        return allocationDao.searchByRoomId(roomId);
    }

    @Override
    public int update(Allocation allocation){
        int rs = allocationDao.updateByPrimaryKeySelective(allocation);
        if(rs > 0){
            sqlSession.commit();
        }else {
            sqlSession.rollback();
        }
        return rs;
    }

}
